package com.cskaoyan.config;

import com.cskaoyan.realm.MallToken;
import com.cskaoyan.realm.MobileToken;
import jdk.nashorn.internal.parser.Token;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author LiaoLong
 * @date 2021-05-12 11:24
 */
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> originRealms = this.getRealms();

        String type = null;
        if (authenticationToken instanceof MallToken){
            MallToken token = (MallToken) authenticationToken;
            type = token.getType();
        }
        if (authenticationToken instanceof MobileToken){
            MobileToken token = (MobileToken) authenticationToken;
            type = token.getType();
        }

        ArrayList<Realm> realms = new ArrayList<Realm>();
        for (Realm originRealm : originRealms) {
            /*
            getName获取的是originRealm的类名,
            判断的就是类名是否包含MallToken传入的type,
            这里的type指的就是哪一个realm
             */
            if (originRealm.getName().toLowerCase().contains(type)){
                realms.add(originRealm);
            }
        }
        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
